package com.hbt.android.kotlin.service

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.hbt.android.kotlin.R
import kotlinx.android.synthetic.main.learn_service.*

class LearnServiceActivity :AppCompatActivity() {

    private var myBinder: LearnService2.MyBinder? = null
    private var connection: ServiceConnection? = null
    private val TAG = "LearnServiceActivity"


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.learn_service)

        // 保持所启动的service的IBinder对象，同时定义一个ServiceConnection对象
        connection = object :ServiceConnection {

            // activity和service连接成功
            override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
                Log.e(TAG, "LearnService2 activity和service连接成功")
                myBinder = service as LearnService2.MyBinder
            }

            // activity和service断开连接
            override fun onServiceDisconnected(name: ComponentName?) {
                Log.e(TAG, "LearnService2 activity和service断开连接")
            }

        }


        // binder是运行一些和activity生命周期相等的任务，比如跨进程的通信
//        val intent = Intent(this, LearnService2::class.java)
//        bindService(intent, connection!!, Context.BIND_AUTO_CREATE)

        // android8.0以上，使用 startForegroundService 启动
        val intent = Intent(this, LearnService2::class.java)
        Handler().postDelayed(Runnable {
            startService(Intent(this@LearnServiceActivity, LearnService2::class.java))
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(intent)
            } else {
                startService(intent)
            }

        }, 10*1000)

        // 启动service
        start_service.setOnClickListener {
            val count = myBinder?.getCount()
            Log.e(TAG, "count: ${count}")
        }

        // 停止service
        stop_service.setOnClickListener {
            unbindService(connection!!)
        }


        // startService 是运行一些后台任务， 比如播放音乐
//        // 启动service
//        start_service.setOnClickListener {
//            val intent = Intent(this, LearnService::class.java)
//            startService(intent)
//        }
//
//        // 停止service
//        stop_service.setOnClickListener {
//            val intent = Intent(this, LearnService::class.java)
//            stopService(intent)
//        }
    }

    /**
     * 销毁的时候需要将service解绑
     */
    override fun onDestroy() {
        super.onDestroy()
        unbindService(connection!!)
    }
}